﻿@{
    ViewBag.Title = "jqGrid in ASP.NET MVC - Dummy [Batch updates]";

    var grid = new Lib.Web.Mvc.JQuery.JqGrid.JqGridHelper<jqGrid.JeffSogolov.Models.DummyViewModel>("dummy",
        dataType: Lib.Web.Mvc.JQuery.JqGrid.JqGridDataTypes.Json,
        methodType: Lib.Web.Mvc.JQuery.JqGrid.JqGridMethodTypes.Post,
        onGridComplete: "$.onGridComplete",
        pager: true,
        rowsNumber: 10,
        sortingName: "Id",
        sortingOrder: Lib.Web.Mvc.JQuery.JqGrid.JqGridSortingOrders.Asc,
        url: Url.Action("FindDummy"),
        width: 1077,
        viewRecords: true
    );
}
<button id="btnBatchUpdate">Batch update</button><br /><br />
@grid.GetHtml()

@section JavaScript {
    <script src="@Url.Content("~/Scripts/jquery.json-2.2.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            @grid.GetJavaScript()
            $('#btnBatchUpdate').button({ icons: { primary: 'ui-icon-disk' } }).click(function() {
                var batch = new Array();
                var dataIds = $('#dummy').jqGrid('getDataIDs');
                for (var i = 0; i < dataIds.length; i++) {
                    try {
	                    $('#dummy').jqGrid('saveRow', dataIds[i], false, 'clientArray');
                        var data = $('#dummy').jqGrid('getRowData', dataIds[i]);
                        data.Id = dataIds[i];
                        if (data.Updated == "Yes") {
                            data.Updated = true;
                            batch.push(data);
                        }
                    }
                    catch (ex) {
                        //If you are using editRules it might end up with exception
                        $('#dummy').jqGrid('restoreRow', dataIds[i]);
                    }
                }
                $.ajax({
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    url: '@Url.Action("BatchUpdateDummies", "Home")',
                    dataType: 'json',
                    data: $.toJSON(batch),
                    success: function(result) {
                        if (result) {
                            $('#dummy').trigger('reloadGrid'); 
                        } else {
                            alert('Batch Update Failed');
                        }
                    }
                });
            });
        });

        $.onGridComplete = function() {
            var rowIds = $("#dummy").jqGrid('getDataIDs');
            for (var i = 0;i < rowIds.length; i++) {
	            $("#dummy").jqGrid('editRow', rowIds[i], false);
            }
        };
    </script>
}